<template>
  <div>
    <m-container class="order"
                 :pagination-visible="false"
                 :current.sync="query.current"
                 :size.sync="query.size"
                 :total.sync="query.total">

      <DeliveryOrderFrom v-model="query"
                         slot="form" />

      <template slot="content">
        <el-tabs v-model="query.orderStatus"
                 @tab-click="handleTabClick">
          <el-tab-pane name="-1">
            <span slot="label">
              <div class="order__quickly">
                <span class="name">{{ quicklyName }}</span>
                <el-dropdown trigger="click"
                             @click.native.stop>
                  <i class="el-icon-arrow-down el-icon--right"></i>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="item of quicklyOption"
                                      @click.native="setQuicklyDate(item.value)"
                                      :key="item.value">{{ item.label }}</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
            </span>
          </el-tab-pane>
          <el-tab-pane label="待付款"
                       name="0"> </el-tab-pane>
          <el-tab-pane label="待发货"
                       name="1"> </el-tab-pane>
          <el-tab-pane label="待提货"
                       name="3"> </el-tab-pane>
          <el-tab-pane label="已完成"
                       name="4"> </el-tab-pane>
          <el-tab-pane label="已关闭"
                       name="5"> </el-tab-pane>
        </el-tabs>
        <DeliveryOrderTable @table-function="tableFunction"
                            :data="orders"
                            :query.sync="query"
                            :checked-item.sync="checkedItem"
                            :controlOption="getControlOption(query.orderStatus)" />
      </template>
    </m-container>

    <OrderDetailModal v-model="detailVisible"
                      :detail="orderDetail"
                      :need-tabs="true"
                      :is-delivery="true"
                      :type="detailType"
                      @reset="handleSeeDetail" />

    <RemarkModal v-model="remarklVisible"
                 title="备注"
                 :current-order="currentOrder"
                 :orderIds="orderIds"
                 @onOk="handleRemarks"
                 @onCancel="toggleRemarklVisible" />

    <DeliverySendModal v-model="sendModalVisible"
                       :current-order="currentOrder"
                       :logisticsPrinterVos="logisticsPrinterVos"
                       :logistics-company="logisticsCompany"
                       @reset="getLogisticsCompany"
                       @onConfirm="confirm" />

    <DeliveryPrintModal v-model="printModalVisible"
                        :logisticsPrinterVos="logisticsPrinterVos"
                        :logistics-company="logisticsCompany"
                        @reset="getLogisticsCompany"
                        @onConfirm="confirm" />
  </div>
</template>

<script lang="ts">
import { Vue, Component, Watch } from "vue-property-decorator";
import DeliveryOrderFrom from "./components/DeliveryOrderFrom.vue";
import DeliveryOrderTable from "./components/DeliveryOrderTable.vue";
import OrderDetailModal from "./components/detail/Index.vue";
import DeliverySendModal from "./components/DeliverySendModal.vue";
import RemarkModal from "./components/RemarkModal.vue";
import DeliveryPrintModal from "./components/DeliveryPrintModal.vue";

import { deliveryOrderQuery, filterEmpty } from "./common/order";
import { getLogisticsCompany } from "@/api/logistics/logistics";

import {
  getOrders,
  getOrderDetail,
  remarks,
  close,
  printDeliver,
  getLogisticsWait
} from "@/api/order";
import cloneDeep from "lodash/cloneDeep";
import debounce from "lodash/debounce";
import { isClose } from "./common/order";

Component.registerHooks(["beforeRouteEnter", "beforeRouteUpdate"]);

@Component({
  components: {
    DeliveryOrderFrom,
    OrderDetailModal,
    RemarkModal,
    DeliveryOrderTable,
    DeliverySendModal,
    DeliveryPrintModal,
  },
})
export default class DeliveryOrder extends Vue {
  query = cloneDeep(deliveryOrderQuery);

  /** 操作栏选项 */
  defaultContorlOption = [
    {
      label: "批量备注",
      value: "remark",
    },
  ];

  /** 待提货操作选项 */
  waitContorlOption = [
    {
      label: "批量备注",
      value: "remark",
    },
  ];

  /** 待付款操作选项 */
  waitPayContorlOption = [
    {
      label: "批量备注",
      value: "remark",
    },
    {
      label: "批量关闭",
      value: "close",
    },
  ];

  /** tab[0]选项 */
  quicklyOption = [
    { label: "近一个月订单", value: "0" },
    { label: "近三个月订单", value: "1" },
    { label: "全部订单", value: "2" },
  ];

  /** 表格数据 */
  data = [];

  /** 选择的订单ID组 */
  orderIds = [];

  /** 订单详情modal */
  detailVisible = false;

  /** 留言modal */
  remarklVisible = false;

  /** 发货modal显示隐藏 */
  sendModalVisible = false;

  /** 打印modal显示隐藏 */
  printModalVisible = false;

  /** 订单详情 */
  orderDetail = {};

  /** 表格选中条目 */
  checkedItem = [];

  /** 当前选中的订单 */
  currentOrder = null;

  // 详情是否显示tab
  needTabs = false;

  /** 显示类型，主要用去驱动详情modal的ui变化 */
  detailType = "1";

  /** 物流公司 */
  logisticsCompany = [];

  /** 打印机列表 */
  logisticsPrinterVos = [];

  /** 物流公司map */
  get logisticsCompanyMap() {
    const map = {};
    this.logisticsCompany.forEach(item => {
      map[item.code] = item.name;
    });
    return map;
  }

  get orders() {
    return this.data.map(item => {
      item.close = isClose(item.status);
      return item;
    });
  }

  /** 表格选中条目ID组 */
  get selectedIds() {
    return this.checkedItem.map(item => item.orderId);
  }

  get quicklyName() {
    return this.quicklyOption.find(
      item => item.value === this.query.quicklyDate,
    ).label;
  }

  /** 监听query变化 */
  @Watch("query", { deep: true })
  handleQueryChange(v) {
    this.getOrders(filterEmpty(filterEmpty({ ...this.$route.query, ...v })));
  }

  /** 获取订单 */
  beforeRouteEnter(to, form, next) {
    const query = filterEmpty(
      Object.assign(cloneDeep(deliveryOrderQuery), to.query),
    );
    getOrders(query)
      .then(res => {
        const { list, ...other } = res.data;
        next(vm => {
          Object.assign(vm.query, query, other);
          vm.data = list;
        });
      })
      .catch(() => {
        alert("列表获取失败,请稍后再试");
      });
  }

  created() {
    this.getLogisticsCompany();
  }

  /** 获取物流公司及打印机 */
  getLogisticsCompany() {
    getLogisticsCompany()
      .then(res => {
        this.logisticsCompany = res.data.logisticsCompanyVos;
        this.logisticsPrinterVos = res.data.LogisticsPrinterVos;
      })
      .catch(err => {
        this.$message.warning(err);
      });
  }

  /** 确认批量发货 */
  confirm(data) {
    if (!data.orderIds.length) {
      data.orderIds = this.checkedItem.map(item => item.orderId);
    }

    printDeliver(data)
      .then(() => {
        this.$message.success("发货成功");
        this.getOrders(Object.assign({}, this.query, this.$route.query));
        this.hideModal();
      })
      .catch(err => {
        this.$message.warning(err || "发货失败");
      });
  }

  /** 查看物流 */
  viewLogistics() {
    this.detailType = "2";
    this.detailVisible = true;
  }

  /** 获取按钮选项 */
  getControlOption(type) {
    return (
      {
        ["-1"]: this.waitContorlOption,
        0: this.waitPayContorlOption,
        1: this.waitContorlOption,
      }[type] || this.defaultContorlOption
    );
  }

  /** 获取订单列表 */
  getOrders = debounce(function(q, cb?) {
    getOrders(q)
      .then(res => {
        const { list, ...other } = res.data;
        Object.assign(this.query, other);
        this.data = list;
        if (cb) {
          cb();
        }
      })
      .catch(err => {
        this.$message.warning(err || "订单列表获取失败");
      });
  }, 50);

  /**
   * 监听table传来的事件
   * @param {name} 事件名 remark | close | detail
   */
  tableFunction(name, data, isLogistics) {
    console.log(name)
    switch (name) {
      case "remark":
        return this.triggerRemark(data);
      case "close":
        return this.handleClose(data);
      case "detail":
        return this.handleSeeDetail(data, isLogistics);
      case "print":
        return this.togglePrintisible();
      case "send":
        this.send(data);
        return;
    }
  }

  /** 发货 */
  async send(data) {
    try {
      const { data: len } = await getLogisticsWait();

      if (!len) {
        return this.$message.info("当前暂无待发货订单");
      }

      const orderIds = this.checkedItem.map(item => item.orderId).join(",");

      const waitLen = this.orders.filter(
        item =>
          orderIds.includes(item.orderId) && item.status === "WAIT_FOR_SEND",
      ).length;

      if (!waitLen && !data) {
        return this.$message.info("您没有选择待发货订单");
      }

      data
        ? this.toggleSendVisible(data)
        : this.$router.push(`/order/delivery/send?orderIds=${orderIds}`);
    } catch (err) {
      this.$message.warning("未发货订单状态获取失败");
    }
  }

  /**
   * 查看详情
   */
  async handleSeeDetail(orderData, isLogistics) {
    if (isLogistics) {
      this.needTabs = true;
      this.detailType = "2";
    } else {
      this.detailType = "1";
      this.needTabs = false;
    }

    if (orderData.orderId) {
      this.toggleDetailModal();
    }

    getOrderDetail(orderData.orderId || orderData.id)
      .then(res => {
        this.orderDetail = res.data;
      })
      .catch(err => {
        this.$message.warning(err || "订单详情获取失败");
      });
    //
  }

  /**
   * 关闭
   * @param {orderData} 订单数据 如果没有参数为批量操作
   */
  handleClose(orderData?: any) {
    this.$confirm("确定关闭订单？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        const orderIds = orderData
          ? [orderData.orderId]
          : [...this.selectedIds];
        close(orderIds)
          .then(() => {
            this.getOrders(Object.assign({}, this.query, this.$route.query));
            this.$message.success("关闭成功");
          })
          .catch(err => {
            this.$message.warning(err || "关闭失败");
          });
      })
      .catch(() => {
        //
      });
  }

  /**
   * 备注
   * @param {orderData} 订单数据 如果没有参数为批量操作
   */
  handleRemarks(form?: any) {
    remarks({ orderIds: this.orderIds, ...form })
      .then(() => {
        this.getOrders(Object.assign({}, this.query, this.$route.query));
        this.toggleRemarklVisible();
        this.$message.success("备注成功");
      })
      .catch(err => {
        this.$message.warning(err || "备注失败");
      });
  }

  setQuicklyDate(v) {
    this.query.quicklyDate = v;
  }

  toggleDetailModal() {
    this.detailVisible = !this.detailVisible;
    if(!this.detailVisible){
      this.detailType = "1"
    }
  }

  toggleRemarklVisible() {
    this.remarklVisible = !this.remarklVisible;
  }

  hideModal() {
    this.sendModalVisible = false;

    this.printModalVisible = false;
  }

  toggleSendVisible(data) {
    this.currentOrder = data;
    this.sendModalVisible = !this.sendModalVisible;
  }

  togglePrintisible() {
    this.printModalVisible = !this.printModalVisible;
  }

  handleTabClick({ name: orderStatus }) {
    Object.assign(this.query, {
      ...deliveryOrderQuery,
      orderStatus,
      current: 1,
      deliverId: "",
      quicklyDate: this.query.quicklyDate,
    });
  }

  triggerRemark(orderData) {
    this.currentOrder = orderData;
    this.orderIds = this.currentOrder
      ? [this.currentOrder.orderId]
      : [...this.selectedIds];

    this.toggleRemarklVisible();
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/styles/order/order.scss";
</style>
